package com.zc.app.sys.controller;

import com.zc.app.shiro.utils.JsonUtils;
import com.zc.app.sys.dao.peer.SystemMenuPeer;
import com.zc.app.sys.dao.peer.SystemUserPeer;
import com.zc.app.sys.service.SystemMenuService;
import com.zc.app.sys.service.SystemUserService;
import com.zc.framework.common.bean.AjaxResult;
import com.zc.framework.common.bean.MyPageInfo;
import com.zc.framework.system.BaseController;
import com.zc.framework.web.view.JxlsExcelView;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zc on 2016/12/15.
 */
@Controller
@RequestMapping("/sys/menu")
public class SystemMenuController extends BaseController {

    private static Logger logger = LogManager.getLogger(SystemMenuController.class);

    @Autowired
    private SystemMenuService systemMenuService;

    @Autowired
    private SystemUserService systemUserService;

    @InitBinder({ "sysMenuQuery" })
    public void initBinderQueryMenu(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("sysMenuQuery.");
    }

    @InitBinder({ "sysMenu" })
    public void initBinderSystemMenu(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("sysMenu.");
    }

//    @RequiresPermissions("sysuser:list:view")
    @RequestMapping(value = "/", method = {RequestMethod.GET})
    public ModelAndView index(SystemMenuPeer menuPeer){
        ModelAndView modelAndView = new ModelAndView("/admin/sys/menu/index");
        return modelAndView;
    }


//    @RequiresPermissions("sysuser:list:view")
    @RequestMapping(value = "/list", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public MyPageInfo<SystemMenuPeer> search(@ModelAttribute("sysMenu")SystemMenuPeer menuPeer) throws InvocationTargetException, IllegalAccessException {
        if(menuPeer==null){
            menuPeer = new SystemMenuPeer();
        }
        MyPageInfo<SystemMenuPeer> pageInfo = systemMenuService.getMenus(menuPeer, menuPeer.getPage(),menuPeer.getRows());
        logger.info("pageInfo:"+pageInfo);
        return pageInfo;
    }

    @RequestMapping(value = "/parentMenu", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public List<SystemMenuPeer> getParentMenu() throws InvocationTargetException, IllegalAccessException {
        List<SystemMenuPeer> rsList = systemMenuService.getParentMenu();
        logger.info("pageInfo:"+rsList);
        return rsList;
    }

    @RequestMapping(value = "/download", method = {RequestMethod.POST,RequestMethod.GET})
    public ModelAndView  download(@ModelAttribute("sysMenu")SystemMenuPeer menuPeer,
                         HttpServletRequest request,
                         HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, URISyntaxException {
        if (menuPeer == null) {
            menuPeer = new SystemMenuPeer();
        }
        MyPageInfo<SystemMenuPeer> pageInfo = systemMenuService.getMenus(menuPeer, menuPeer.getPage(), menuPeer.getRows());
        logger.info("pageInfo:" + pageInfo);

        Map<String, Object> model = new HashMap<>();
        model.put("dataList", pageInfo.getRows());
        return new ModelAndView(new JxlsExcelView("templeate/excel/menu_template.xls","out_menu_template.xls"), model);
    }



    @RequestMapping(value = "/edit", method = {RequestMethod.GET})
    public ModelAndView edit(@RequestParam(value = "pageType",required = false)String pageType,
                             @RequestParam(value = "menuId",required = false)Integer menuId){
        ModelAndView modelAndView = new ModelAndView("/admin/sys/menu/edit");
        SystemMenuPeer menuPeer = new SystemMenuPeer();
        if("edit".equals(pageType)
                && menuId!=null){
            menuPeer = systemMenuService.queyMenuById(menuId);
        }
        modelAndView.addObject("sysMenu", menuPeer);
        modelAndView.addObject("pageType",pageType);
        return modelAndView;
    }

    @RequestMapping(value = "/view", method = {RequestMethod.GET})
    public ModelAndView view(@RequestParam(value = "menuId",required = false)Integer menuId){
        ModelAndView modelAndView = new ModelAndView("/admin/sys/menu/view");
        SystemMenuPeer menuPeer = new SystemMenuPeer();
        if(menuId!=null){
            menuPeer = systemMenuService.queyMenuById(menuId);
        }
        modelAndView.addObject("sysMenu", menuPeer);
        return modelAndView;
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult delete(@RequestParam(value = "menuId")Integer[] menuIds,
                             HttpServletRequest request,
                             HttpServletResponse response, Model model) {

        if(menuIds==null || menuIds.length==0){
            return fail(false,"用户ID不能为空");
        }
        for(Integer menuId: menuIds){
            systemMenuService.deleteByPrimaryKey(menuId);
        }
        return success(true);
    }


    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult save(@ModelAttribute("sysMenu") SystemMenuPeer systemMenu,
                            @RequestParam(value = "pageType",required = false)String pageType) throws IOException {

        SystemUserPeer user = systemUserService.getCurrentUser();

        logger.info(JsonUtils.writeValueAsString(user));

        if("edit".equals(pageType)){
            if (systemMenu.getMenuId()==null) {
                return fail(false, "账号ID不能为空!");
            }
            systemMenu.setUpdateBy(user.getUserName());
            systemMenuService.updateMenu(systemMenu);
            return success(true);
        }

        if (StringUtils.isEmpty(systemMenu.getMenuCode())) {
            return fail(false, "菜单代码不能为空!");
        }
        if (StringUtils.isEmpty(systemMenu.getMenuName())) {
            return fail(false, "名字不能为空!");
        }

        systemMenu.setCreateBy(user.getUserName());
        systemMenu.setUpdateBy(user.getUserName());
        systemMenuService.createMenu(systemMenu);
        return success(true);
    }

}
